package com.qy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qy.entity.PackageInfo;
import com.qy.entity.PackageInfoVO;
import com.qy.entity.PromotionPolicy;
import com.qy.entity.UserCommProfile;
import com.qy.mapper.PackageInfoMapper;
import com.qy.mapper.PromotionPolicyMapper;
import com.qy.mapper.UserCommProfileMapper;
import com.qy.service.ITaocanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Arrays;

@Slf4j
@Service
@RequiredArgsConstructor
public class TaocanServiceImpl implements ITaocanService {

    private final UserCommProfileMapper userCommProfileMapper;
    private final PackageInfoMapper packageInfoMapper;
    private final PromotionPolicyMapper promotionPolicyMapper;

    @Override
    public List<UserCommProfile> listUser(){
        List<UserCommProfile> userCommProfiles = this.userCommProfileMapper.selectList(new LambdaQueryWrapper<>());
        return userCommProfiles;
    }

    @Override
    public List<PackageInfoVO> listTaocan(){
        log.info("in");
        List<PackageInfoVO> packageInfoVOS = new ArrayList<>();
        List<PackageInfo> packageInfos = this.packageInfoMapper.selectList(new LambdaQueryWrapper<>());
        for (PackageInfo packageInfo : packageInfos) {
            PackageInfoVO packageInfoVO = new PackageInfoVO();
            BeanUtils.copyProperties(packageInfo, packageInfoVO);

            String packageId = packageInfo.getPackageId();
            List<PromotionPolicy> promotionPolicies = this.promotionPolicyMapper.selectList(new LambdaQueryWrapper<PromotionPolicy>().like(PromotionPolicy::getTargetPackages, packageId));
            packageInfoVO.setPromotionPolicyList(promotionPolicies);

            packageInfoVOS.add(packageInfoVO);
        }
        return packageInfoVOS;
    }

    @Override
    public String taocanRecommend(String content) {
        StringBuilder recommendPromot = new StringBuilder();
        recommendPromot.append("以下是用户信息：");
        String userInfoByContent = getUserInfoByContent(content);
        recommendPromot.append(userInfoByContent);

        recommendPromot.append("以下是套餐信息：");
        String allPackageInfoAsString = getAllPackageInfoAsString();
        recommendPromot.append(allPackageInfoAsString);

        recommendPromot.append("以下是优惠信息：");
        String allPromotionPolicyAsString = getAllPromotionPolicyAsString();
        recommendPromot.append(allPromotionPolicyAsString);

        recommendPromot.append("根据上述信息为用户给出合适的套餐。");

        if(StringUtils.isBlank(userInfoByContent)||StringUtils.isBlank(allPromotionPolicyAsString)||StringUtils.isBlank(allPackageInfoAsString)){
            return "error";
        }

        log.info(recommendPromot.toString());
        return recommendPromot.toString();
    }

    public UserCommProfile getUserInfoObjByContent(String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }

        // 从content中提取用户名（这里使用简单的正则表达式，实际应用可能需要更复杂的逻辑）
        // 假设用户名称可能出现在"我是XXX"、"我叫XXX"等模式中
        String userName = extractUserName(content);

        if (StringUtils.isNotBlank(userName)) {
            // 根据用户名查询UserCommProfile表
            LambdaQueryWrapper<UserCommProfile> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserCommProfile::getUserName, userName);
            UserCommProfile userProfile = userCommProfileMapper.selectOne(wrapper);
            // 将查询出的内容拼接成一句话
            return userProfile;
        }

        return null;
    }


    @Override
    public String getUserInfoByContent(String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }

        // 从content中提取用户名（这里使用简单的正则表达式，实际应用可能需要更复杂的逻辑）
        // 假设用户名称可能出现在"我是XXX"、"我叫XXX"等模式中
        String userName = extractUserName(content);

        if (StringUtils.isNotBlank(userName)) {
            // 根据用户名查询UserCommProfile表
            LambdaQueryWrapper<UserCommProfile> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserCommProfile::getUserName, userName);
            UserCommProfile userProfile = userCommProfileMapper.selectOne(wrapper);
            // 将查询出的内容拼接成一句话
            return buildUserInfoSentence(userProfile);
        }

        return null;
    }

    /**
     * 将用户信息拼接成一句话
     */
    private String buildUserInfoSentence(UserCommProfile userProfile) {
        if (userProfile == null) {
            return null;
        }
        
        StringBuilder sentence = new StringBuilder();
        sentence.append("用户")
                .append(userProfile.getUserName())
                .append(", 年龄")
                .append(userProfile.getAge())
                .append("岁, 职业为")
                .append(userProfile.getOccupation())
                .append(", 月度通信预算")
                .append(userProfile.getMonthlyBudget())
                .append("元, 流量需求等级")
                .append(userProfile.getNetDemand())
                .append(", 通话需求等级")
                .append(userProfile.getCallDemand())
                .append(",")
                .append(userProfile.getNeedIntlRoam() ? "需要国际漫游" : "不需要国际漫游")
                .append(", 合约偏好")
                .append(userProfile.getPreferContract());
        
        if (StringUtils.isNotBlank(userProfile.getNeedVas())) {
            sentence.append(", 希望获得的增值服务：")
                    .append(userProfile.getNeedVas());
        }
        
        if (StringUtils.isNotBlank(userProfile.getExtraRemark())) {
            sentence.append(", 其他个性化需求：")
                    .append(userProfile.getExtraRemark());
        }
        
        sentence.append("。");
        return sentence.toString();
    }
    
    /**
     * 从文本中提取用户名
     */
    private String extractUserName(String content) {
        // 简单的正则表达式提取用户名
        // 可以根据实际需求调整提取逻辑
        if (content.contains("我是")) {
            int start = content.indexOf("我是") + 2;
            int end = content.length();
            // 寻找第一个可能的结束位置（标点符号、空格等）
            for (int i = start; i < content.length(); i++) {
                if (!Character.isLetterOrDigit(content.charAt(i)) && content.charAt(i) != '·') {
                    end = i;
                    break;
                }
            }
            return content.substring(start, end).trim();
        }

        if (content.contains("我叫")) {
            int start = content.indexOf("我叫") + 2;
            int end = content.length();
            for (int i = start; i < content.length(); i++) {
                if (!Character.isLetterOrDigit(content.charAt(i)) && content.charAt(i) != '·') {
                    end = i;
                    break;
                }
            }
            return content.substring(start, end).trim();
        }

        // 如果没有明显的模式，可以返回内容的前几个字符作为可能的用户名
        return content.length() > 10 ? content.substring(0, 10).trim() : content.trim();
    }
    
    @Override
    public Map<String, Object> getUserTypeCategories() {
        List<PackageInfo> packages = packageInfoMapper.selectList(new LambdaQueryWrapper<>());
        Map<String, Integer> userTypeCountMap = new HashMap<>();
        Map<String, String> userTypeDescMap = new HashMap<>();
        
        // 初始化用户群体描述
        userTypeDescMap.put("学生", "适合学生群体的套餐");
        userTypeDescMap.put("商务人士", "适合商务人士的套餐");
        userTypeDescMap.put("退休人员", "适合退休人员的套餐");
        userTypeDescMap.put("自由职业者", "适合自由职业者的套餐");
        userTypeDescMap.put("企业管理人员", "适合企业管理人员的套餐");
        
        // 统计每个用户群体的套餐数量
        for (PackageInfo pkg : packages) {
            String[] userTypes = pkg.getTargetUsers().split(",");
            for (String userType : userTypes) {
                userType = userType.trim();
                if (userTypeDescMap.containsKey(userType)) {
                    userTypeCountMap.put(userType, userTypeCountMap.getOrDefault(userType, 0) + 1);
                }
            }
        }
        
        // 构建返回数据
        List<Map<String, Object>> categories = new ArrayList<>();
        for (Map.Entry<String, String> entry : userTypeDescMap.entrySet()) {
            String userType = entry.getKey();
            Map<String, Object> category = new HashMap<>();
            category.put("name", userType);
            category.put("description", entry.getValue());
            category.put("count", userTypeCountMap.getOrDefault(userType, 0));
            categories.add(category);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "获取用户群体分类成功");
        result.put("data", categories);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getPriceRangeCategories() {
        List<PackageInfo> packages = packageInfoMapper.selectList(new LambdaQueryWrapper<>());
        
        // 定义价格区间
        String[] priceRanges = {"0-50元", "50-100元", "100-200元", "200元以上"};
        String[] priceRangeDescs = {"经济实惠的套餐", "性价比高的套餐", "高端优质的套餐", "豪华尊享的套餐"};
        int[] priceRangeCounts = new int[4];
        
        // 统计每个价格区间的套餐数量
        for (PackageInfo pkg : packages) {
            Double price = pkg.getPrice().doubleValue();
            if (price < 50) {
                priceRangeCounts[0]++;
            } else if (price < 100) {
                priceRangeCounts[1]++;
            } else if (price < 200) {
                priceRangeCounts[2]++;
            } else {
                priceRangeCounts[3]++;
            }
        }
        
        // 构建返回数据
        List<Map<String, Object>> categories = new ArrayList<>();
        for (int i = 0; i < priceRanges.length; i++) {
            Map<String, Object> category = new HashMap<>();
            category.put("name", priceRanges[i]);
            category.put("description", priceRangeDescs[i]);
            category.put("count", priceRangeCounts[i]);
            categories.add(category);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "获取价格区间分类成功");
        result.put("data", categories);
        
        return result;
    }
    
    @Override
    public String getAllPackageInfoAsString() {
        // 查询所有套餐信息
        List<PackageInfo> packageInfoList = packageInfoMapper.selectList(null);
        
        if (packageInfoList == null || packageInfoList.isEmpty()) {
            return "暂无套餐信息。";
        }
        
        StringBuilder allPackages = new StringBuilder("现有套餐信息如下：");
        
        for (int i = 0; i < packageInfoList.size(); i++) {
            PackageInfo packageInfo = packageInfoList.get(i);
            allPackages.append(buildPackageInfoSentence(packageInfo));
            
            // 如果不是最后一个套餐，添加分隔符
            if (i < packageInfoList.size() - 1) {
                allPackages.append("；");
            }
        }
        
        allPackages.append("。");
        return allPackages.toString();
    }
    
    @Override
    public String getAllPromotionPolicyAsString() {
        // 查询所有优惠政策信息
        List<PromotionPolicy> promotionPolicyList = promotionPolicyMapper.selectList(null);
        
        if (promotionPolicyList == null || promotionPolicyList.isEmpty()) {
            return "暂无优惠政策信息。";
        }
        
        StringBuilder allPromotions = new StringBuilder("现有优惠政策如下：");
        
        for (int i = 0; i < promotionPolicyList.size(); i++) {
            PromotionPolicy promotionPolicy = promotionPolicyList.get(i);
            allPromotions.append(buildPromotionPolicySentence(promotionPolicy));
            
            // 如果不是最后一个优惠政策，添加分隔符
            if (i < promotionPolicyList.size() - 1) {
                allPromotions.append("；");
            }
        }
        
        allPromotions.append("。");
        return allPromotions.toString();
    }
    
    @Override
    public boolean addTaocan(PackageInfo packageInfo) {
        if (packageInfo == null) {
            log.error("添加套餐失败：套餐信息为空");
            return false;
        }
        
        try {
            // 查询表中最大的packageId
            LambdaQueryWrapper<PackageInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(PackageInfo::getPackageId);
            wrapper.orderByDesc(PackageInfo::getPackageId);
            wrapper.last("LIMIT 1");
            PackageInfo maxPackage = packageInfoMapper.selectOne(wrapper);
            
            // 生成新的packageId
            String newPackageId;
            if (maxPackage != null && maxPackage.getPackageId() != null) {
                try {
                    // 尝试将现有ID转换为数字并加1
                    String packageId = maxPackage.getPackageId().trim();
                    packageId = packageId.replace("P", "");
                    int maxId = Integer.parseInt(packageId);

                    newPackageId = "P"+String.format("%03d", maxId + 1);
                } catch (NumberFormatException e) {
                    // 如果ID不是纯数字，使用时间戳作为新ID
                    log.warn("现有套餐ID非数字格式，使用时间戳生成新ID");
                    newPackageId = String.valueOf(System.currentTimeMillis());
                }
            } else {
                // 如果表为空，从1开始
                newPackageId = "P001";
            }
            
            // 设置新的packageId
            packageInfo.setPackageId(newPackageId);
            
            // 使用MyBatis-Plus的insert方法添加套餐信息
            int result = packageInfoMapper.insert(packageInfo);
            log.info("添加套餐成功：套餐ID={}, 套餐名称={}", packageInfo.getPackageId(), packageInfo.getName());
            return result > 0;
        } catch (Exception e) {
            log.error("添加套餐失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean editTaocan(PackageInfo packageInfo) {
        if (packageInfo == null) {
            log.error("编辑套餐失败：套餐信息为空");
            return false;
        }
        
        if (packageInfo.getPackageId() == null || packageInfo.getPackageId().trim().isEmpty()) {
            log.error("编辑套餐失败：套餐ID为空");
            return false;
        }
        
        try {
            // 使用MyBatis-Plus的updateById方法更新套餐信息
            int result = packageInfoMapper.updateById(packageInfo);
            log.info("编辑套餐成功：套餐ID={}, 套餐名称={}", packageInfo.getPackageId(), packageInfo.getName());
            return result > 0;
        } catch (Exception e) {
            log.error("编辑套餐失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean packageExists(String packageId) {
        if (StringUtils.isBlank(packageId)) {
            log.error("检查套餐是否存在失败：套餐ID为空");
            return false;
        }
        
        try {
            LambdaQueryWrapper<PackageInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PackageInfo::getPackageId, packageId);
            PackageInfo packageInfo = packageInfoMapper.selectOne(wrapper);
            return packageInfo != null;
        } catch (Exception e) {
            log.error("检查套餐是否存在失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean addPromotion(PromotionPolicy promotionPolicy) {
        if (promotionPolicy == null) {
            log.error("添加优惠政策失败：优惠政策信息为空");
            return false;
        }
        
        try {
            int result = promotionPolicyMapper.insert(promotionPolicy);
            log.info("添加优惠政策成功：优惠ID={}, 优惠名称={}", promotionPolicy.getPromotionId(), promotionPolicy.getName());
            return result > 0;
        } catch (Exception e) {
            log.error("添加优惠政策失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean promotionExists(String promotionId) {
        if (StringUtils.isBlank(promotionId)) {
            log.error("检查优惠政策是否存在失败：优惠ID为空");
            return false;
        }
        
        try {
            LambdaQueryWrapper<PromotionPolicy> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PromotionPolicy::getPromotionId, promotionId);
            PromotionPolicy promotionPolicy = promotionPolicyMapper.selectOne(wrapper);
            return promotionPolicy != null;
        } catch (Exception e) {
            log.error("检查优惠政策是否存在失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public List<PromotionPolicy> listPromotions() {
        log.info("查询所有优惠政策列表");
        try {
            return promotionPolicyMapper.selectList(null);
        } catch (Exception e) {
            log.error("查询优惠政策列表失败：{}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean editPromotion(PromotionPolicy promotionPolicy) {
        if (promotionPolicy == null) {
            log.error("编辑优惠政策失败：优惠政策信息为空");
            return false;
        }
        
        if (promotionPolicy.getPromotionId() == null || promotionPolicy.getPromotionId().trim().isEmpty()) {
            log.error("编辑优惠政策失败：优惠ID为空");
            return false;
        }
        
        try {
            // 使用MyBatis-Plus的updateById方法更新优惠政策信息
            int result = promotionPolicyMapper.updateById(promotionPolicy);
            log.info("编辑优惠政策成功：优惠ID={}, 优惠名称={}", promotionPolicy.getPromotionId(), promotionPolicy.getName());
            return result > 0;
        } catch (Exception e) {
            log.error("编辑优惠政策失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean deletePromotion(String promotionId) {
        if (StringUtils.isBlank(promotionId)) {
            log.error("删除优惠政策失败：优惠ID为空");
            return false;
        }
        
        try {
            // 使用MyBatis-Plus的deleteById方法删除优惠政策
            int result = promotionPolicyMapper.deleteById(promotionId);
            log.info("删除优惠政策成功：优惠ID={}", promotionId);
            return result > 0;
        } catch (Exception e) {
            log.error("删除优惠政策失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 将套餐信息拼接成一句话
     */
    private String buildPackageInfoSentence(PackageInfo packageInfo) {
        if (packageInfo == null) {
            return "";
        }
        
        StringBuilder sentence = new StringBuilder();
        sentence.append("套餐标志：")
                .append(packageInfo.getPackageId())
                .append("，套餐\"")
                .append(packageInfo.getName())
                .append("\"，月费")
                .append(packageInfo.getPrice())
                .append("元，包含")
                .append(packageInfo.getDataLimit())
                .append(packageInfo.getDataUnit())
                .append("流量，")
                .append(packageInfo.getCallMinutes())
                .append("分钟通话，")
                .append(packageInfo.getSmsCount())
                .append("条短信，网络速度等级为")
                .append(packageInfo.getNetworkSpeed())
                .append("，目标用户为")
                .append(packageInfo.getTargetUsers());
        
        if (StringUtils.isNotBlank(packageInfo.getFeatures())) {
            sentence.append(", 附加服务：")
                    .append(packageInfo.getFeatures());
        }
        
        if (StringUtils.isNotBlank(packageInfo.getDescription())) {
            sentence.append(", 描述：")
                    .append(packageInfo.getDescription());
        }
        
        return sentence.toString();
    }
    
    /**
     * 将优惠政策信息拼接成一句话
     */
    private String buildPromotionPolicySentence(PromotionPolicy promotionPolicy) {
        if (promotionPolicy == null) {
            return "";
        }
        
        StringBuilder sentence = new StringBuilder();
        sentence.append("优惠政策\"")
                .append(promotionPolicy.getName())
                .append("\"，适用于套餐")
                .append(promotionPolicy.getTargetPackages())
                .append(",")
                .append("折扣类型为")
                .append("percentage".equals(promotionPolicy.getDiscountType()) ? "百分比折扣" : "固定金额折扣")
                .append("，折扣值为")
                .append(promotionPolicy.getDiscountValue())
                .append("，适用于用户群体")
                .append(promotionPolicy.getEligibility())
                .append("，有效期为")
                .append(promotionPolicy.getValidPeriod());
        
        if (StringUtils.isNotBlank(promotionPolicy.getDescription())) {
            sentence.append(", 描述：")
                    .append(promotionPolicy.getDescription());
        }
        
        return sentence.toString();
    }
}
